package com.upc.feedish;

import androidx.appcompat.app.AppCompatActivity;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.upc.feedish.utils.DeviceViewAdapter;
import com.upc.feedish.utils.SerializableMap;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ManageActivity extends AppCompatActivity {

    private ListView deviceList;
    private List<Map<String, Object>> datalist;
    private DeviceViewAdapter adapter;
    private Handler handler;
    private Toast deleteSuccessToast;
    private Toast failure_Toast;
    private Toast timeOut_Toast;
    private int deviceId;
    private String username;

    Map<String, Object> deviceInfo = new HashMap<String, Object>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1:
                        refresh();
                }

            };
        };
        setContentView(R.layout.activity_manage);

        failure_Toast = Toast.makeText(this,"无设备",Toast.LENGTH_SHORT);
        timeOut_Toast = Toast.makeText(this,"网络连接超时",Toast.LENGTH_SHORT);
        deleteSuccessToast = Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT);

        SharedPreferences sp = getSharedPreferences("data",MODE_PRIVATE);
        username= sp.getString("username","");
        int devicePosition = sp.getInt("devicePosition",0);
        System.out.println("p2"+devicePosition);
        deviceList = findViewById(R.id.deviceList);
        View emptyView = findViewById(R.id.empty);
        deviceList.setEmptyView(emptyView);
        datalist =getData();
        adapter = new DeviceViewAdapter(this,datalist);
        adapter.setSelectItem(devicePosition);
        deviceList.setAdapter(adapter);


        //adapter.setSelectItem(devicePosition);


        deviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                adapter.setSelectItem(position);
                adapter.notifyDataSetInvalidated();

                SharedPreferences.Editor editor = sp.edit();
                editor.putInt("devicePosition",position);
                editor.apply();

                Toast.makeText(ManageActivity.this,"已选择设备",Toast.LENGTH_SHORT).show();
            }
        });


        deviceList.setOnItemLongClickListener((parent, view, position, id) -> {
            deviceInfo = (Map<String, Object>) deviceList.getItemAtPosition(position);//SimpleAdapter返回Map
            deviceId = (int) deviceInfo.get("id");
            String name = (String) deviceInfo.get("name");
            final AlertDialog.Builder normalDialog = new AlertDialog.Builder(ManageActivity.this);
            normalDialog.setTitle("您确认要删除 " + name + " 吗？");
            normalDialog.setMessage("删除后无法恢复");
            normalDialog.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            DeleteDeviceThread deleteDeviceThread = new DeleteDeviceThread();
                            deleteDeviceThread.start();
                        }
                    });
            normalDialog.setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                        }
                    });
            normalDialog.show();
            return true;
        });

    }

    public List<Map<String, Object>> getData() {
        datalist = new ArrayList<Map<String, Object>>();
        GetDeviceThread getDeviceThread = new GetDeviceThread();
        getDeviceThread.start();
        while(getDeviceThread.isAlive());

        return datalist;
    }

    public class GetDeviceThread extends Thread{
        public void run(){
            try {
                String json = "{\"username\":\""+username+"\"}";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://1.116.33.97:8080/getAllDevice")
                        .post(RequestBody.create(MediaType.parse("application/json"),json))
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body().string();
                JSONObject jsonObject=JSONObject.parseObject(responseData);

                int code=(int)jsonObject.get("code");
                if(code == 100){
                    JSONArray jsonArray = (JSONArray) jsonObject.get("data");
                    JSONObject Devices;
                    for(int i=0;i<jsonArray.size();i++){
                        Devices = (JSONObject) jsonArray.get(i);
                        datalist.add(i,Devices);
                    }
                }
                else{
                    failure_Toast.show();
                }
            }catch (Exception e){
                e.printStackTrace();
                timeOut_Toast.show();
            }
        }
    }

    public class DeleteDeviceThread extends Thread{
        public void run(){
            try {
                String json = "{\"id\":\""+deviceId+"\"}";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://1.116.33.97:8080/deleteDevice")
                        .post(RequestBody.create(MediaType.parse("application/json"),json))
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body().string();
                JSONObject jsonObject=JSONObject.parseObject(responseData);

                int code=(int)jsonObject.get("code");
                if(code == 100){
                    deleteSuccessToast.show();

                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
                else{
                    timeOut_Toast.show();
                }
            }catch (Exception e){
                e.printStackTrace();
                timeOut_Toast.show();
            }
        }
    }

    public void refresh() {
        //刷新list
        datalist.clear();
        datalist = getData();
        adapter = new DeviceViewAdapter(this, datalist);
        deviceList.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onResume(){
        super.onResume();
        refresh();
    }

    public void addDevice(View view) {
        Intent intent = new Intent(ManageActivity.this,AddDeviceActivity.class);
        startActivity(intent);
    }
}